//
//  GKDetailViewController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2018/9/5.
//  Copyright © 2018 wangws1990. All rights reserved.
//

import UIKit
import MBProgressHUD
import RxCocoa
import RxRelay
import RxSwift
class GKDetailViewController: YNPageViewController,YNPageViewControllerDataSource {
    class func vcWithBookId(bookId:String) -> GKDetailViewController{
        let config = YNPageConfigration.defaultConfig();
        config?.headerViewCouldScale = true
        config?.scrollMenu = true
        config?.showNavigation = false
        config?.showTabbar = true
        config?.pageStyle = .suspensionCenter
        config?.headerViewScaleMode = .top;
        
        config?.aligmentModeCenter = true;
        config?.selectedItemColor = moya.appColor;
        config?.selectedItemFont = UIFont.systemFont(ofSize: 17);
        config?.itemFont = UIFont.systemFont(ofSize: 15)
        config?.menuHeight = 44;
        config?.itemMargin = 40;
        config?.lineColor = moya.appColor;
        config?.normalItemColor = UIColor.appx333333();
        config?.suspenOffsetY = NAVI_BAR_HIGHT;
        config?.lineWidthEqualFontWidth = true;
        config?.scrollViewBackgroundColor = UIColor.appxffffff()
        let vc :GKDetailViewController = GKDetailViewController(controllers: [GKCenterController(bookId: bookId)], titles: ["推荐"], config:config);
        vc.delegate = vc;
        vc.dataSource = vc;
        vc.headerView = vc.topView;
        vc.bookId = bookId;
        return vc
    }
    private lazy var topView : GKDetailTopView = {
        let topView :GKDetailTopView = GKDetailTopView.instanceView()
        topView.frame = CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: 150 + NAVI_BAR_HIGHT)
        return topView;
    }()
    private lazy var tabView: GKDetailTabView = {
        let tab :GKDetailTabView = GKDetailTabView.instanceView()
        tab.favBtn.addTarget(self, action:#selector(favAction(sender:)), for: .touchUpInside)
        tab.readBtn.addTarget(self, action: #selector(readAction), for: .touchUpInside)
        return tab
    }()
    lazy var naviView: GKDetailNaviView = {
        let tab :GKDetailNaviView = GKDetailNaviView.instanceView()
        tab.backBtn.addTarget(self, action: #selector(goBackAction), for: .touchUpInside)
        return tab
    }()
    private var bookId:String? = nil
    private var height: CGFloat = 0;
    private var model : GKBookInfo?{
        didSet{
            guard let item = model else { return }
            self.topView.model = item
            self.naviView.model = item
            self.controllersM.forEach { (vc) in
                if let ctrl = vc as? GKCenterController{
                    ctrl.model = item
                }
//                if let ctrl = vc as? GKChapterController{
//                    ctrl.bookModel = item
//                }
            }
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        loadUI();
        loadData()
        loadFavData()
    }
    override func viewDidAppear(_ animated: Bool) {
        super .viewDidAppear(animated)
        
    }
    private func loadUI(){
        self.view.backgroundColor = UIColor.appxffffff()
        self.fd_prefersNavigationBarHidden = true
        self.view.addSubview(self.tabView);
        self.tabView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview();
            make.height.equalTo(49)
            make.bottom.equalToSuperview().offset(-TAB_BAR_ADDING);
        }
        self.view.addSubview(self.naviView)
        self.naviView.snp.makeConstraints { (make) in
            make.left.right.top.equalToSuperview()
            make.height.equalTo(NAVI_BAR_HIGHT)
        }
        self.naviView.setAlpha(value: 0)
    }
    func loadFavData(){
        guard let bookid = self.bookId else { return  }
        let have = GKShelfData.haveData(bookid)
        self.tabView.favBtn.isSelected = have
    }
    func loadHistoryData(){
        guard let item = self.model else { return }
        GKHistoryData.updateBook(bookId: item.bookId ?? "", bookInfo: item.toJSONString() ?? "") { success in
            
        }
    }
    @objc private func readAction(){
        guard let item = self.model else { return }
        guard let model = GKBook.deserialize(from: item.toJSONString()) else { return }
        GKJump.jumpToNovel(bookId:model.bookId)
    }
    @objc private func favAction(sender:GKFavButton) {
        guard let item = self.model else { return  }
        if sender.isSelected == false {
            sender.select()
            GKShelfData.insertBookModel(bookDetail: item) { (success) in
                if success{
                    self.tabView.favBtn.isSelected = true;
                    MBProgressHUD.showToast("收藏成功")
                }
            }
        }else{
            guard let bookid = self.bookId else { return  }
            ATAlertView.showAlertView(title: "是否取消收藏？", message:"", normals:["取消"], hights:["确定"]) { (title, index) in
                if index > 0{
                    sender.deselect()
                
                    GKShelfData.deleteBookModel(bookId:bookid, sucesss: { (success) in
                        if success{
                            MBProgressHUD.showToast("取消收藏成功");
                            self.tabView.favBtn.isSelected = false;
                        }
                    })
                }
            }
        }
    }
    @objc private func goBackAction(){
        self.goBack();
    }
    private func loadData(){
        guard let bookid = self.bookId else { return  }
        ApiMoya.request(target: .bookDetail(bookid)) { json in
            guard let model = GKBookInfo.deserialize(from: json.rawString()) else{
                return
            }
            self.model = model
            self.loadHistoryData()
        } failure: { error in
            
        }
    }
    func pageViewController(_ pageViewController: YNPageViewController!, pageFor index: Int) -> UIScrollView! {
        if let vc = pageViewController.controllersM[index] as? UIViewController{
            if let ctrl = vc as? BaseTableViewController{
                return ctrl.tableView
            }
            if let ctrl = vc as? BaseConnectionController{
                return ctrl.collectionView
            }
        }
        return UIScrollView()
    }
    override var preferredStatusBarStyle: UIStatusBarStyle{
        return self.naviView.titleLab.isHidden ? .lightContent : .default;
    }
}
extension GKDetailViewController :YNPageViewControllerDelegate{
    func pageViewController(_ pageViewController: YNPageViewController!, contentOffsetY: CGFloat, progress: CGFloat) {
        self.naviView.setAlpha(value: progress)
        self.setNeedsStatusBarAppearanceUpdate()
    }
}
